import request from "@/common/request/index.js";
import store from '@/store';
import base from '@/config/baseUrl';
import {router} from './../router'

let version_code = '';

let $http = new request({
	baseUrl: base.baseUrl,
	fileUrl: base.baseUrl,
	defaultUploadUrl: "/client/api/upload",
	header: {
		'Content-Type': 'application/json',
		'Accept': 'application/json',
	}
});

//请求开始拦截器
$http.requestStart = function(options) {
	
	console.log("请求开始", options);
	// 判断是否需要进行登录验证
	if (options && options.auth) {
		
		if (!store.state.AuthToken) {
			
			return "-1"
		}
	}
	let urlType = /^(http|https):\/\//.test(options.url);
	
	if (options.method == "FILE") {
		options.url = urlType ? options.url : this.fileUrl + options.url;
	} else {
		options.url = urlType ? options.url : this.baseUrl + options.url;
	}

	if (options.load) {
		store.commit("setLoadingShow", true);
	}

	
	if (options.method == "FILE" && options.maxSize) {
		let maxSize = options.maxSize;
		for (let item of options.files) {
			if (item.size > maxSize) {
				setTimeout(() => {
					uni.showToast({
						title: "图片过大，请重新上传",
						icon: "none"
					});
				}, 500);
				return false;
			}
		}
	}
	// #ifdef APP-PLUS

	if (version_code) {
		options.header['version_code'] = version_code;
	}
	// #endif
	
	if (store.state.AuthToken) {
		options.header['Cookie'] = ('PHPSESSID=' + store.state.AuthToken).trim();
	};
	// options.header['token'] ='eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MTcwNzQsImV4cCI6bnVsbCwidXNlcl9uYW1lIjoiMmVkMmEwYjZhZTBiNDQzNDliOWFiN2RhZWIwOWY0ZWUiLCJqdGkiOm51bGwsImNsaWVudF9pZCI6ImFwaS1jbGllbnQiLCJzY29wZSI6WyJhbGwiXX0.CSl01wyS_t3DuAH19q4HwMlOau-k0iPw7IVjzbiPJTw2hkrjEV8Ce6T4-vTT0G-xQRUIDHTgpJAJVJ30OXt--92NJtGdPwceyZ8rjnKPs9yVIl45yyAlNPbMqjTJxlDhFEPbrR1e4fOnrFGV6IN6edet9ZWkzPkSrAv_njbSTgI';
	return options;
}

$http.requestEnd = function(options) {
	
	if (options.load) {
		
		store.commit("setLoadingShow", false);
	}
}
let loginPopupNum = 0;

$http.dataFactory = async function(res) {
	
	if (res.response.statusCode && res.response.statusCode == 200) {

		let httpData = res.response.data;

		if (typeof(httpData) == "string") {
			httpData = JSON.parse(httpData);
		}
		if (httpData.result == 1) {
			// #ifdef APP-PLUS
			var cookieValue = res.response.header["Set-Cookie"];
			cookieValue = cookieValue.replace("[", "").replace("]", "");
			// #endif
			// #ifdef H5
			var cookieValue = document.cookie;
			// #endif
			var arr = cookieValue.split(";");
			var userid;
			//遍历数组
			for(var i=0;i<arr.length;i++){
				var value = arr[i].split("=");
				if(value[0] == "PHPSESSID"){
					store.commit("setToken", value[1])
					break;
				}
			}
			
			return Promise.resolve(httpData);
		} else if (httpData.status == 401) {

			if (res.resend <= 2 && res.resend > 0) {
				// store.commit("userInfo", tokenResult);
				let result = await $http.request({
					url: res.url,
					data: res.data,
					method: res.method,
					header: res.header,
					isPrompt: res.isPrompt, 
					load: res.load, 
					isFactory: res.isFactory,
					resend: res.resend -= 1
				});
				// 返回正确的结果(then接受数据)
				return Promise.resolve(result);
			}
			store.commit("emptyUserInfo");
			if (loginPopupNum <= 0) {
				loginPopupNum++;
				uni.showModal({
					title: '温馨提示',
					content: "请登录用户",
					confirmText: "去登录",
					cancelText: "再逛会",
					success: function(res) {
						loginPopupNum--;
						if (res.confirm) {

						
						}
					}
				});
			}
			return Promise.reject({
				statusCode: 0,
				errMsg: "【request】" + (httpData.data || httpData.message),
				data: res.data
			});
		} else if (httpData.status == 311) {
			uni.showModal({
				title: '温馨提示',
				content: httpData.message,
				confirmText: '去新增',
				cancelText: "再逛会",
				success: function(res) {
					if (res.confirm) {
						uni.navigateTo({
							url: '/pages/CollectionAddress/CollectionAddress'
						})
					}
				}
			});
		} else if (httpData.status == 500) {
			uni.showToast({
				title: httpData.message,
				icon: "none"
			});
			return Promise.reject({
				statusCode: httpData.status,
				errMsg: "【request】" + (httpData.message),
				data: res.data
			});
		} else if (httpData.status == 403) {
			
			uni.showModal({
				// title: "请先设置支付密码",
				content: "请先设置支付密码",
				success() {
					uni.navigateTo({
						url: "pages/prefile/resetSecondaryPassword/resetSecondaryPassword"
					})
				},
			})
		} else if (httpData.status == 2000) {
			return Promise.reject({
				statusCode: httpData.status,
				errMsg: "【request】" + (httpData.message),
				data: res.data
			});
		} else if (httpData.result === 400){
			store.commit("LOGIN_TIP", true);
			// uni.showToast({
			// 	title: httpData.msg,
			// 	icon: "none",
			// 	duration: 3000
			// });
			
			return Promise.reject({
				statusCode: httpData.status,
				errMsg: "【request】" + (httpData.msg),
				data: res.data
			});
			// uni.setStorageSync('fromLogin', router);
		} else { //其他错误提示   
				
				if(httpData.msg == '请登录') {
					console.log(789789, router.currentRoute);
					if(router.currentRoute.path != '/pages/personal/login/login') {
						if (router.currentRoute.path == '/pages/index/goods-detail/goods-detail' || router.currentRoute.path == '/pages/mall/goods-detail/goods-detail') {
							uni.navigateTo({
								url: '/pages/personal/login/login?reurl=' + router.currentRoute.path + '&id=' + router.currentRoute.query.id
							})
						} else {
							uni.navigateTo({
								url: '/pages/personal/login/login'
							})
						}
					}
				}
				
				uni.showToast({
					title: httpData.msg,
					icon: "none",
					duration: 3000
				});
			

			// 返回错误的结果(catch接受数据)
			return Promise.reject({
				statusCode: httpData.status,
				errMsg: httpData.msg,
				data: res.data
			});
		}

	

	} else if (res.response.statusCode == 403) {
		if (loginPopupNum <= 0) {
			loginPopupNum++;
			uni.showModal({
				title: '温馨提示',
				content: "登录过期~",
				confirmText: "去登录",
				cancelText: "再逛会",
				success: function(res) {
					loginPopupNum--;
					if (res.confirm) {
						uni.navigateTo({
							url: "/pages/personal/login/login"
						})
					}
				}
			});
		}
	
	} else {

		// 返回错误的结果(catch接受数据)
		return Promise.reject({
			statusCode: res.response.statusCode,
			errMsg: "【request】数据工厂验证不通过",
			data: res.data
		});
	}
};
// 错误回调
$http.requestError = function(e) {
	// e.statusCode === 0 是参数效验错误抛出的
	if (e.statusCode === 0) {
		throw e;
	} else if (e.statusCode === 2000 || e.statusCode === 500) {
		console.log(e);
	} else if (e.statusCode === -1 && loginPopupNum <= 0) {
		loginPopupNum++;
		
	} else {
		
		console.log(e);
	
	}
}


export default $http
